"""
API使用示例
"""
import requests
import json
import time


def test_api_health():
    """测试API健康检查"""
    print("=== 测试API健康检查 ===")
    
    try:
        response = requests.get("http://localhost:8000/")
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
    except Exception as e:
        print(f"连接失败: {e}")


def test_add_document():
    """测试添加文档"""
    print("\n=== 测试添加文档 ===")
    
    # 创建测试文档
    test_file = "api_test_doc.txt"
    with open(test_file, "w", encoding="utf-8") as f:
        f.write("""
        数据挖掘是从大量数据中发现有用信息和模式的过程。
        它包括数据预处理、模式发现、模式评估和知识表示等步骤。
        数据挖掘技术广泛应用于商业智能、科学研究、医疗诊断等领域。
        """)
    
    # 添加文档
    data = {
        "file_path": test_file,
        "kb_name": "api_test_kb",
        "chunk_size": 500,
        "chunk_overlap": 100,
        "splitter_name": "ChineseRecursiveTextSplitter"
    }
    
    try:
        response = requests.post(
            "http://localhost:8000/documents/add",
            json=data
        )
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
        
        # 清理测试文件
        import os
        os.remove(test_file)
        
    except Exception as e:
        print(f"请求失败: {e}")


def test_search():
    """测试搜索功能"""
    print("\n=== 测试搜索功能 ===")
    
    data = {
        "query": "什么是数据挖掘？",
        "kb_name": "api_test_kb",
        "top_k": 3,
        "score_threshold": 0.3
    }
    
    try:
        response = requests.post(
            "http://localhost:8000/search",
            json=data
        )
        print(f"状态码: {response.status_code}")
        result = response.json()
        
        print(f"查询: {result['query']}")
        print(f"知识库: {result['kb_name']}")
        print(f"结果数量: {result['total']}")
        
        for i, item in enumerate(result['results'], 1):
            print(f"\n结果 {i}:")
            print(f"  内容: {item['content'][:100]}...")
            print(f"  分数: {item['score']:.4f}")
            print(f"  元数据: {item['metadata']}")
            
    except Exception as e:
        print(f"请求失败: {e}")


def test_batch_add():
    """测试批量添加文档"""
    print("\n=== 测试批量添加文档 ===")
    
    # 创建多个测试文档
    documents = [
        ("batch_doc1.txt", "机器学习算法包括监督学习、无监督学习和强化学习。"),
        ("batch_doc2.txt", "深度学习使用神经网络来模拟人脑的学习过程。"),
        ("batch_doc3.txt", "自然语言处理技术使计算机能够理解和生成人类语言。"),
    ]
    
    for filename, content in documents:
        with open(filename, "w", encoding="utf-8") as f:
            f.write(content)
    
    file_paths = [filename for filename, _ in documents]
    
    data = {
        "file_paths": file_paths,
        "kb_name": "batch_test_kb",
        "chunk_size": 300,
        "chunk_overlap": 50,
        "splitter_name": "ChineseRecursiveTextSplitter"
    }
    
    try:
        response = requests.post(
            "http://localhost:8000/documents/add_batch",
            json=data
        )
        print(f"状态码: {response.status_code}")
        result = response.json()
        
        print(f"总文件数: {result['total_files']}")
        print(f"成功文件数: {result['successful_files']}")
        
        # 清理测试文件
        import os
        for filename, _ in documents:
            os.remove(filename)
            
    except Exception as e:
        print(f"请求失败: {e}")


def test_knowledge_base_management():
    """测试知识库管理"""
    print("\n=== 测试知识库管理 ===")
    
    try:
        # 列出知识库
        response = requests.get("http://localhost:8000/knowledge_bases")
        print(f"知识库列表: {response.json()}")
        
        # 获取知识库信息
        response = requests.get("http://localhost:8000/knowledge_bases/api_test_kb/info")
        print(f"知识库信息: {response.json()}")
        
        # 获取配置信息
        response = requests.get("http://localhost:8000/config")
        print(f"配置信息: {response.json()}")
        
    except Exception as e:
        print(f"请求失败: {e}")


def test_clear_knowledge_base():
    """测试清空知识库"""
    print("\n=== 测试清空知识库 ===")
    
    data = {
        "kb_name": "api_test_kb"
    }
    
    try:
        response = requests.post(
            "http://localhost:8000/knowledge_bases/clear",
            json=data
        )
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
        
    except Exception as e:
        print(f"请求失败: {e}")


def main():
    """主函数"""
    print("Data Embedding API 使用示例")
    print("请确保API服务已启动: uvicorn data_embedding.api.routes:app --host 0.0.0.0 --port 8000")
    print("=" * 50)
    
    # 等待API服务启动
    print("等待API服务启动...")
    time.sleep(2)
    
    # 运行测试
    test_api_health()
    test_add_document()
    test_search()
    test_batch_add()
    test_knowledge_base_management()
    test_clear_knowledge_base()
    
    print("\n所有测试完成！")


if __name__ == "__main__":
    main() 